package com.atguigu.gulimall.gulimallauthserver.controller;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.gulimallauthserver.feign.MemberFeignService;
import com.atguigu.gulimall.gulimallauthserver.vo.SocialUserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理社交登录请求
 *
 * @author xiaoping
 * @create 2020/6/30 18:28
 * @since 1.0.0
 */
@Slf4j
@Controller
public class OAuth2Controller {

    @Autowired
    MemberFeignService memberFeignService;

    /**
     * 社交登录回调
     * @param code
     * @return
     */
    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, RedirectAttributes redirectAttributes, HttpSession session) {

        try {
            //根据code获取accessToken
            Map<String, Object> map = new HashMap<>();
            map.put("client_id", "4200884488");
            map.put("client_secret", "b1e306511b0d706a852e865ca32b9e1b");
            map.put("grant_type", "authorization_code");
            map.put("redirect_uri", "http://auth.gulimall.com/oauth2.0/weibo/success");
            map.put("code", code);

            String post = HttpUtil.post("https://api.weibo.com/oauth2/access_token", map);
            //判断是否存在token
            if (!StringUtils.isEmpty(post) && !post.contains("error_code")) {
                SocialUserVo socialUserVo = JSON.parseObject(post, SocialUserVo.class);
                //远程登录
                R r = memberFeignService.oauthLogin(socialUserVo);
                if (r.getCode() == 0) {
                    MemberRespVo data = r.getData("data", new TypeReference<MemberRespVo>() {});
                    log.info("登录成功：用户：{}",data.toString());
                    //数据存入SpringSession
                    session.setAttribute(AuthServerConstant.LOGIN_USER, data);
                    //登录成功跳转回首页
                    return "redirect:http://gulimall.com";
                }
            }
            System.out.println("回调错误：" + post);
        }catch (Exception e){
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("errors", "登录超时或异常，请重新登录");
        }
        return "redirect:http://auth.gulimall.com/login.html";
    }


}
